<template>
	<view class="page join-group-page">
		<!-- 自定义导航栏 -->
		<ob-navbar title="搜索群聊" :show-back="true" />
		
		<view class="content">
			<!-- 搜索区域 -->
			<view class="search-section">
				<view class="search-box">
					<input 
						v-model="searchKeyword"
						type="text" 
						placeholder="输入群聊名称、群号或群邀请码"
						class="search-input"
						@confirm="handleSearch"
						@input="onSearchInput"
					/>
					<button 
						class="search-btn" 
						:disabled="!searchKeyword.trim() || isSearching"
						@click="handleSearch"
					>
						{{ isSearching ? '搜索中' : '搜索' }}
					</button>
				</view>
				<text class="search-tip">支持搜索群名称、群号或群邀请码</text>
			</view>
			
			<!-- 快速加入方式 -->
			<view class="quick-join-section">
				<view class="section-header">
					<text class="section-title">快速加入</text>
				</view>
				
				<view class="quick-options">
					<view class="quick-option" @click="scanQRCode">
						<view class="option-icon">Q</view>
						<text class="option-title">扫码加入</text>
						<text class="option-desc">扫描群聊二维码</text>
					</view>
					
					<view class="quick-option" @click="joinByInviteCode">
						<view class="option-icon">I</view>
						<text class="option-title">邀请码加入</text>
						<text class="option-desc">输入群聊邀请码</text>
					</view>
				</view>
			</view>
			
			<!-- 搜索结果 -->
			<view v-if="searchResults.length > 0" class="search-results-section">
				<view class="section-header">
					<text class="section-title">搜索结果</text>
					<text class="result-count">{{ searchResults.length }} 个群聊</text>
				</view>
				
				<view class="results-list">
					<view 
						v-for="group in searchResults" 
						:key="group.id"
						class="group-item"
						@click="viewGroupDetail(group)"
					>
						<image :src="group.avatar" class="group-avatar" mode="aspectFill" />
						<view class="group-info">
							<text class="group-name">{{ group.name }}</text>
							<text class="group-desc">{{ group.memberCount }}人 · {{ group.description || '暂无群介绍' }}</text>
							<view class="group-tags">
								<text v-if="group.isPublic" class="tag public">公开</text>
								<text v-else class="tag private">私有</text>
								<text v-if="group.needApproval" class="tag approval">需要验证</text>
							</view>
						</view>
						<button 
							class="join-btn" 
							:class="{ 
								'joined': group.status === 'joined',
								'pending': group.status === 'pending'
							}"
							:disabled="group.status === 'joined' || group.status === 'pending'"
							@click.stop="joinGroup(group)"
						>
							{{ getJoinButtonText(group) }}
						</button>
					</view>
				</view>
			</view>
			
			<!-- 空状态 */
			<view v-if="showEmptyState" class="empty-state">
				<ob-empty 
					:image="'/static/images/empty-search.png'"
					title="未找到相关群聊"
					description="尝试输入完整的群名称或群号"
				/>
			</view>
			
			<!-- 推荐群聊 -->
			<view v-if="recommendedGroups.length > 0" class="recommended-section">
				<view class="section-header">
					<text class="section-title">推荐群聊</text>
				</view>
				
				<view class="recommended-list">
					<view 
						v-for="group in recommendedGroups" 
						:key="group.id"
						class="group-item"
						@click="viewGroupDetail(group)"
					>
						<image :src="group.avatar" class="group-avatar" mode="aspectFill" />
						<view class="group-info">
							<text class="group-name">{{ group.name }}</text>
							<text class="group-desc">{{ group.memberCount }}人 · {{ group.description }}</text>
							<view class="group-tags">
								<text class="tag public">推荐</text>
								<text v-if="group.category" class="tag category">{{ group.category }}</text>
							</view>
						</view>
						<button 
							class="join-btn" 
							:disabled="group.status === 'joined'"
							@click.stop="joinGroup(group)"
						>
							{{ group.status === 'joined' ? '已加入' : '加入' }}
						</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 邀请码输入弹窗 -->
		<view v-if="showInviteModal" class="invite-modal" @click="showInviteModal = false">
			<view class="invite-content" @click.stop>
				<view class="invite-header">
					<text class="invite-title">输入邀请码</text>
					<text class="close-btn" @click="showInviteModal = false">×</text>
				</view>
				<view class="invite-body">
					<input 
						v-model="inviteCode"
						type="text" 
						placeholder="请输入群聊邀请码"
						class="invite-input"
						maxlength="20"
					/>
					<button 
						class="confirm-btn" 
						:disabled="!inviteCode.trim()"
						@click="joinByCode"
					>
						确认加入
					</button>
				</view>
			</view>
		</view>
		
		<!-- 群详情弹窗 -->
		<view v-if="showDetailModal" class="detail-modal" @click="showDetailModal = false">
			<view class="detail-content" @click.stop>
				<view class="detail-header">
					<text class="close-btn" @click="showDetailModal = false">×</text>
				</view>
				<view v-if="selectedGroup" class="detail-body">
					<image :src="selectedGroup.avatar" class="detail-avatar" mode="aspectFill" />
					<text class="detail-name">{{ selectedGroup.name }}</text>
					<text class="detail-desc">{{ selectedGroup.description || '暂无群介绍' }}</text>
					
					<view class="detail-info">
						<view class="info-item">
							<text class="info-label">群成员</text>
							<text class="info-value">{{ selectedGroup.memberCount }}人</text>
						</view>
						<view class="info-item">
							<text class="info-label">创建时间</text>
							<text class="info-value">{{ formatDate(selectedGroup.createdAt) }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">群类型</text>
							<text class="info-value">{{ selectedGroup.isPublic ? '公开群' : '私有群' }}</text>
						</view>
					</view>
					
					<button 
						class="detail-join-btn" 
						:class="{ 
							'joined': selectedGroup.status === 'joined',
							'pending': selectedGroup.status === 'pending'
						}"
						:disabled="selectedGroup.status === 'joined' || selectedGroup.status === 'pending'"
						@click="joinGroup(selectedGroup)"
					>
						{{ getJoinButtonText(selectedGroup) }}
					</button>
				</view>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import groupApi from '../../api/group.js'

// 响应式数据
const searchKeyword = ref('')
const searchResults = ref([])
const recommendedGroups = ref([])
const isSearching = ref(false)
const isLoading = ref(false)
const hasSearched = ref(false)
const showInviteModal = ref(false)
const showDetailModal = ref(false)
const inviteCode = ref('')
const selectedGroup = ref(null)

// 计算属性
const showEmptyState = computed(() => {
	return hasSearched.value && searchResults.value.length === 0 && !isSearching.value
})

// 生命周期
onMounted(() => {
	loadRecommendedGroups()
})

// 方法
const onSearchInput = () => {
	// 实时搜索防抖
	clearTimeout(window.searchTimer)
	window.searchTimer = setTimeout(() => {
		if (searchKeyword.value.trim()) {
			handleSearch()
		}
	}, 500)
}

const handleSearch = async () => {
	if (!searchKeyword.value.trim() || isSearching.value) return
	
	try {
		isSearching.value = true
		hasSearched.value = true
		
		const response = await groupApi.searchGroups({
			keyword: searchKeyword.value.trim()
		})
		
		searchResults.value = response.list || []
	} catch (error) {
		console.error('搜索群聊失败:', error)
		uni.showToast({
			title: '搜索失败',
			icon: 'none'
		})
	} finally {
		isSearching.value = false
	}
}

const loadRecommendedGroups = async () => {
	try {
		const response = await groupApi.getRecommendedGroups()
		recommendedGroups.value = response.list || []
	} catch (error) {
		console.error('加载推荐群聊失败:', error)
	}
}

const getJoinButtonText = (group) => {
	switch (group.status) {
		case 'joined':
			return '已加入'
		case 'pending':
			return '等待审核'
		default:
			return '加入'
	}
}

const joinGroup = async (group) => {
	if (group.status === 'joined' || group.status === 'pending') return
	
	try {
		isLoading.value = true
		
		const response = await groupApi.joinGroup({
			groupId: group.id,
			message: `我想加入群聊"${group.name}"`
		})
		
		if (response.success) {
			if (group.needApproval) {
				group.status = 'pending'
				uni.showToast({
					title: '申请已发送，等待管理员审核',
					icon: 'success'
				})
			} else {
				group.status = 'joined'
				uni.showToast({
					title: '加入成功',
					icon: 'success'
				})
				
				// 跳转到群聊
				setTimeout(() => {
					uni.navigateTo({
						url: `/pages/message/chat?conversationId=${response.conversationId}&type=group`
					})
				}, 1000)
			}
		}
		
		// 关闭详情弹窗
		showDetailModal.value = false
		
	} catch (error) {
		console.error('加入群聊失败:', error)
		uni.showToast({
			title: '加入失败',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

const viewGroupDetail = (group) => {
	selectedGroup.value = group
	showDetailModal.value = true
}

const scanQRCode = () => {
	uni.scanCode({
		success: async (res) => {
			try {
				// 解析二维码内容
				const qrData = JSON.parse(res.result)
				if (qrData.type === 'group' && qrData.groupId) {
					// 根据群ID获取群信息并加入
					await joinGroupById(qrData.groupId)
				} else {
					throw new Error('无效的群聊二维码')
				}
			} catch (error) {
				console.error('扫码加入失败:', error)
				uni.showToast({
					title: '无效的群聊二维码',
					icon: 'none'
				})
			}
		},
		fail: (error) => {
			console.error('扫码失败:', error)
			uni.showToast({
				title: '扫码失败',
				icon: 'none'
			})
		}
	})
}

const joinByInviteCode = () => {
	inviteCode.value = ''
	showInviteModal.value = true
}

const joinByCode = async () => {
	if (!inviteCode.value.trim()) return
	
	try {
		isLoading.value = true
		showInviteModal.value = false
		
		const response = await groupApi.joinGroupByInviteCode({
			inviteCode: inviteCode.value.trim()
		})
		
		if (response.success) {
			uni.showToast({
				title: '加入成功',
				icon: 'success'
			})
			
			// 跳转到群聊
			setTimeout(() => {
				uni.navigateTo({
					url: `/pages/message/chat?conversationId=${response.conversationId}&type=group`
				})
			}, 1000)
		}
		
	} catch (error) {
		console.error('邀请码加入失败:', error)
		uni.showToast({
			title: '邀请码无效或已过期',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

const joinGroupById = async (groupId) => {
	try {
		isLoading.value = true
		
		// 先获取群信息
		const groupInfo = await groupApi.getGroupInfo(groupId)
		
		// 直接加入群聊
		await joinGroup(groupInfo)
		
	} catch (error) {
		console.error('通过ID加入群聊失败:', error)
		uni.showToast({
			title: '加入失败',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

const formatDate = (timestamp) => {
	if (!timestamp) return ''
	const date = new Date(timestamp)
	return date.toLocaleDateString('zh-CN')
}
</script>

<style lang="scss" scoped>
.join-group-page {
	background: #FAFAFA;
	min-height: 100vh;
}

.content {
	padding: 0 15px;
}

.search-section {
	background: #FFFFFF;
	padding: 20px;
	margin: 10px 0;
	border-radius: 8px;
}

.search-box {
	display: flex;
	gap: 10px;
	align-items: center;
	margin-bottom: 10px;
}

.search-input {
	flex: 1;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 6px;
	padding: 12px 15px;
	font-size: 14px;
	height: 44px;
	box-sizing: border-box;
}

.search-btn {
	background: #495057;
	color: #FFFFFF;
	border: none;
	border-radius: 6px;
	padding: 12px 24px;
	font-size: 14px;
	height: 44px;
	min-width: 80px;
	flex-shrink: 0;
	box-sizing: border-box;
	
	&:disabled {
		background: #CED4DA;
		color: #6C757D;
	}
}

.search-tip {
	font-size: 12px;
	color: #999999;
}

.quick-join-section,
.search-results-section,
.recommended-section {
	background: #FFFFFF;
	margin: 10px 0;
	border-radius: 8px;
	overflow: hidden;
}

.section-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
}

.result-count {
	font-size: 14px;
	color: #999999;
}

.quick-options {
	padding: 10px 20px;
}

.quick-option {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: #F8F9FA;
	}
}

.option-icon {
	width: 40px;
	height: 40px;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
	font-weight: 600;
	color: #6C757D;
	margin-right: 15px;
}

.option-title {
	font-size: 16px;
	color: #333333;
	font-weight: 500;
	margin-bottom: 2px;
}

.option-desc {
	font-size: 12px;
	color: #999999;
}

.results-list,
.recommended-list {
	padding: 0 20px;
}

.group-item {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: #F8F9FA;
	}
}

.group-avatar {
	width: 50px;
	height: 50px;
	border-radius: 8px;
	margin-right: 12px;
}

.group-info {
	flex: 1;
	min-width: 0;
}

.group-name {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
	display: block;
	margin-bottom: 4px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.group-desc {
	font-size: 12px;
	color: #666666;
	display: block;
	margin-bottom: 6px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.group-tags {
	display: flex;
	gap: 6px;
}

.tag {
	font-size: 10px;
	padding: 2px 6px;
	border-radius: 8px;
	
	&.public {
		background: #E3F2FD;
		color: #1976D2;
	}
	
	&.private {
		background: #FFF3E0;
		color: #F57C00;
	}
	
	&.approval {
		background: #FCE4EC;
		color: #C2185B;
	}
	
	&.category {
		background: #F3E5F5;
		color: #7B1FA2;
	}
}

.join-btn {
	background: #495057;
	color: #FFFFFF;
	border: none;
	border-radius: 4px;
	padding: 8px 16px;
	font-size: 12px;
	
	&:disabled,
	&.joined,
	&.pending {
		background: #E9ECEF;
		color: #6C757D;
	}
}

.empty-state {
	padding: 50px 20px;
	text-align: center;
}

.invite-modal,
.detail-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.invite-content {
	background: #FFFFFF;
	border-radius: 12px;
	margin: 0 40px;
	max-width: 300px;
	width: 100%;
}

.invite-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #F0F0F0;
}

.invite-title {
	font-size: 18px;
	font-weight: 600;
	color: #333333;
}

.close-btn {
	font-size: 24px;
	color: #999999;
	width: 30px;
	text-align: center;
}

.invite-body {
	padding: 20px;
}

.invite-input {
	width: 100%;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 6px;
	padding: 12px 15px;
	font-size: 14px;
	margin-bottom: 15px;
}

.confirm-btn {
	width: 100%;
	background: #495057;
	color: #FFFFFF;
	border: none;
	border-radius: 6px;
	padding: 12px;
	font-size: 16px;
	
	&:disabled {
		background: #CED4DA;
		color: #6C757D;
	}
}

.detail-content {
	background: #FFFFFF;
	border-radius: 12px;
	margin: 0 40px;
	max-width: 350px;
	width: 100%;
	max-height: 80vh;
	overflow-y: auto;
}

.detail-header {
	display: flex;
	justify-content: flex-end;
	padding: 15px 20px;
}

.detail-body {
	padding: 0 20px 20px;
	text-align: center;
}

.detail-avatar {
	width: 80px;
	height: 80px;
	border-radius: 12px;
	margin-bottom: 15px;
}

.detail-name {
	font-size: 20px;
	font-weight: 600;
	color: #333333;
	display: block;
	margin-bottom: 8px;
}

.detail-desc {
	font-size: 14px;
	color: #666666;
	display: block;
	margin-bottom: 20px;
	line-height: 1.5;
}

.detail-info {
	text-align: left;
	margin-bottom: 20px;
}

.info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
}

.info-label {
	font-size: 14px;
	color: #666666;
}

.info-value {
	font-size: 14px;
	color: #333333;
	font-weight: 500;
}

.detail-join-btn {
	width: 100%;
	background: #495057;
	color: #FFFFFF;
	border: none;
	border-radius: 6px;
	padding: 12px;
	font-size: 16px;
	
	&:disabled,
	&.joined,
	&.pending {
		background: #E9ECEF;
		color: #6C757D;
	}
}
</style>